from django.contrib.auth import login, logout, forms
from django.contrib.auth.hashers import make_password
from django.middleware.csrf import get_token
from numpy.core import unicode

from userinfo.models import UserInfo
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import AllowAny,IsAuthenticated,IsAuthenticatedOrReadOnly  # 权限认证
from rest_framework.authentication import SessionAuthentication  # 用户认证
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from utils import message


# from utils import message as msg

# 在这创建视图功能

# 注册用户
# noinspection PySingleQuotedDocstring
class RegisterUser(APIView):
    # 允许所有用户
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    permission_classes = [AllowAny]

    @staticmethod
    def post(request):
        '''
        接收用户名，密码，邮箱提交注册
        1.用户名，密码，邮箱
        2.生成用户
        3.保存用户
        :param request:
        :return:
        '''

        username = request.data.get("username")
        password = request.data.get("password")
        email = request.data.get("email")

        """
        检查是否在数据库中存在
        user1 = UserInfo.objects.filter(username=username).exists()
        """


        if UserInfo.objects.filter(username=username).exists():
            data = {
                'code': message.ERROR_USERNAME_USED,
                'message': message.GetErrMsg(message.ERROR_USERNAME_USED),
                'data':{
                    'id':UserInfo.objects.get(username=username).id,
                    'username':username,
                    'password':password,
                    'email':email
                }
            }
            return Response(data=data,status=message.SUCCSE)

        if all([username, password]):
            pass
        else:
            data = {
                'code': message.ERROR_PARAM_NOT_COMPLETE,
                'message': message.GetErrMsg(message.ERROR_PARAM_NOT_COMPLETE),
            }
            return Response(data=data, status=message.SUCCSE)

        user = UserInfo.objects.create_user(username=username, password=password, email=email)



        data = {
            'code': message.USER_REGISTER_OK,
            'message': message.GetErrMsg(message.USER_REGISTER_OK),
            'data': {
                'id':user.id,
                'username': username,
                'password': password,
                'email': email
            }
        }
        return Response(data=data, status=message.SUCCSE)


# 登录用户
class LoginUser(APIView):
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    permission_classes = [AllowAny]

    # def get(self,request):
    #     usernames = [user.username for user in UserInfo.objects.all()]
    #     # print(usernames)
    #     return Response(usernames)

    @staticmethod
    def post(request):

        # 判断用户是否登录
        if request.user.is_authenticated:
            data = {
                'code': message.ERROR_USER_ALREADY_LOGGED_IN,
                'message': message.GetErrMsg(message.ERROR_USER_ALREADY_LOGGED_IN),
                'data': {
                    'username': request.user.username
                }
            }
            return Response(data, status=message.SUCCSE)

        # 请求数据提交给 AuthenticationForm 处理
        authentication = forms.AuthenticationForm(data=request.POST)

        # 验证账号密码
        if authentication.is_valid():
            # 验证通过登录
            login(request, authentication.get_user())
            # 返回登录成功信息
            data = {
                'code': message.USER_LOGGED_IN_OK,
                'message': message.GetErrMsg(message.USER_LOGGED_IN_OK),
                'data': {
                    'userinfo': {
                        'id': request.user.id,
                        'username': request.user.username,
                        'is_staff': request.user.is_staff,
                        'is_superuser': request.user.is_superuser

                    },
                    'sessions': request.session.session_key,
                    'csrf_token': get_token(request)
                }
            }

            return Response(data=data, status=200)
        else:
            # 验证失败
            data = {
                'code': message.ERROR_USER_AND_PASSWORD_WRONG,
                'message': message.GetErrMsg(message.ERROR_USER_AND_PASSWORD_WRONG),
                'data': authentication.errors

            }
            return Response(data=data, status=400)


class LogoutUser(APIView):
    permission_classes = [IsAuthenticated]
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)

    @staticmethod
    def get(request):
        # 缓存用户名
        username = request.user.username

        # 退出登录清除缓存
        logout(request)

        # # 重定向到登录页面
        # response = redirect(reverse('blog:LogoutUser'))
        #
        # #清除cookie
        # response.delete_cookie('username')
        # print(response)

        data = {
            'code': message.USER_LOGOUT_OK,
            'message': message.GetErrMsg(message.USER_LOGOUT_OK),
            'data': {
                'username': username
            }
        }
        return Response(data=data, status=message.SUCCSE)



class EditUser(APIView):
    # 权限判断 已经登录 只读
    permission_classes = (IsAuthenticated,)
    # 用户认证
    authentication_classes = (JSONWebTokenAuthentication,SessionAuthentication)


    def put(self,request):
        user = request.data
        id = request.user.id

        # 更新指定id user 信息
        modelsuser = UserInfo.objects.get(id=id)
        modelsuser.set_password(user.get('password')) if user.get('password')!=None else request.user.password
        modelsuser.email = user.get('email') if user.get('email')!=None else request.user.email
        modelsuser.is_staff = user.get('is_staff') if user.get('is_staff')!=None else request.user.is_staff
        modelsuser.nickName = user.get('nickName') if user.get('nickName')!=None else request.user.nickName
        modelsuser.headImg = user.get('headImg') if user.get('headImg')!=None else request.user.headImg
        modelsuser.is_active = True
        modelsuser.save()




        userinfo = {
            'id':user.get('id'),
            'username':user.get('username'),
            'username': user.get('password'),
            'email':user.get('email'),
            'nickname': user.get('nickName'),
            'headImg': unicode(user.get('headImg')),
            'is_superuser': user.get('is_superuser'),
            'is_active': user.get('is_active'),
            'last_login': user.get('last_login'),
            'date_joined': user.get('date_joined'),
        }

        data = {
            'code': message.USER_EDIT_INFO_OK,
            'message': message.GetErrMsg(message.USER_EDIT_INFO_OK),
            'data': userinfo,
        }
        return Response(data=data,status=message.SUCCSE)


class GetUser(APIView):

    # 权限判断 已经登录 只读
    permission_classes = (IsAuthenticated,)
    # 用户认证
    authentication_classes = (JSONWebTokenAuthentication,SessionAuthentication)




    @staticmethod
    def get(request):

        user = request.user

        userinfo = {
            'id':user.id,
            'username':user.username,
            'email':user.email,
            'nickname': user.nickName,
            'headImg': unicode(user.headImg),
            'is_superuser': user.is_superuser,
            'is_active':user.is_active,
            'last_login': user.last_login,
            'date_joined': user.date_joined,

        }



        data = {
            'code': message.USER_SELF_INFO_OK,
            'message': message.GetErrMsg(message.USER_SELF_INFO_OK),
            'data': {
                'username': userinfo
            }
        }

        return Response(data=data,status=message.SUCCSE)
